﻿using Common;
using NB.MGJ.Common;
using NB.MGJ.Model;
using NB.MGJ.Service;
using NB.MGJ.Service.AntiFake;
using NB.MGJ.Service.CodeManage;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace NB.MGJ.Web.Controllers
{
    public partial class CodeManageController
    {

        public DBHController dbh = new DBHController();
        public AntiFakeVerifyService _AntiFakeVerifyService = new AntiFakeVerifyService();
        private GenCodeBatchService _CodeBatchService = new GenCodeBatchService();
        private CodeManageService _codeManageService = new CodeManageService();
        private ManagerService _manager = new ManagerService();

        private DigitcodeService _digService = new DigitcodeService();


        #region 生码 下载

        /// <summary>
        /// 判断生码表是否存在
        /// </summary>
        /// <returns></returns>
        public bool ExistsCodeTable(int pid, string code)
        {
            var models = _CodeBatchService.GetModels(pid, code);
            CodeManage_GenCodeBatch model = _CodeBatchService.GetModel(pid);
            if (model == null || models==0)
            {
                return false;
            }
           
            string table = "antifake_digitcode" + code + model.Batch;
            return _dbhService.TabExists_Code(table);
        }


        /// <summary>
        /// 获取生码文件
        /// 有问题
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportCode(int productBatchId, string code, string englishnum, string num = null)
        {
            try
            {

                //获取该批次的生码类型
                CodeManage_GenCode model = _codeManageService.GetModel(productBatchId);

                string queryField = string.Empty;//需要查询的字段标记
                if (model != null)
                {
                    string[] strType = model.CodeType.Split(',');
                    foreach (string codeType in strType)
                    {
                        if (codeType.Contains("1"))
                        {//防伪码
                            queryField += "Fw_Code,";
                        }
                        if (codeType.Contains("2"))
                        {//管理码
                            queryField += "Wl_Code,";
                        }

                    }
                    var entername = _CodeBatchService.filename(code);
                    var batch = _CodeBatchService.batch(productBatchId);
                    var filenames = entername + batch;
                    if (num == "0" || string.IsNullOrWhiteSpace(num))
                    {
                        return File(ExportCodeByBatch(productBatchId, code, queryField), "application/octet-stream", filenames + ".txt");
                    }
                    return File(ExportCodeByBatch(productBatchId, code, queryField, englishnum, num), "application/octet-stream", filenames + ".txt");
                }
            }
            catch //(Exception ex)
            {
                throw;
            }
            return null;
        }



        public byte[] ExportCodeByBatch(int batchId, string code, string queryField, string serialNum, string _Num)
        {
            try
            {
                CodeManage_GenCodeBatch model = _CodeBatchService.GetModel(batchId);
                Organization_Enterprise Enterprise = _manager.GetEnterpriseModel(code);
                var batch = model.Batch;

                string tabName = "nbcodemain." + AppConst.TablePrefix + code + batch;
                DataTable codeTbl = _CodeBatchService.queryCode(tabName, queryField);
                bool fwIsExist = codeTbl.Columns.Contains("Fw_Code");
                bool wlIsExist = codeTbl.Columns.Contains("Wl_Code");
                string key = AppConst.DigitCodeKey;
                string overrideLine = string.Empty;
                int Num = Convert.ToInt32(_Num);
                string _append = string.Empty;
                for (int j = 0; j < _Num.Length; j++)
                {
                    _append += "0";
                }
                for (int i = 0; i < codeTbl.Rows.Count; i++)
                {
                    DataRow dr = codeTbl.Rows[i];
                    string result = string.Empty;
                    if (fwIsExist)
                    {
                        result += MiMa.Jiami(dr["Fw_Code"].ToString(), key);

                    }
                    if (wlIsExist && fwIsExist)
                    {
                        result += "," + dr["Wl_Code"].ToString() + ",";
                    }
                    if (wlIsExist && !fwIsExist)
                    {
                        result += dr["Wl_Code"].ToString() + ",";
                    }

                    overrideLine += string.Format("{0}{1},{2}{3}", serialNum, (Num++).ToString(_append), result.TrimEnd(','), "\r\n");
                }
                return Encoding.UTF8.GetBytes(overrideLine);
            }
            catch (Exception)
            {
                throw;
            }
        }


        private byte[] ExportCodeByBatch(int productBatchId, string code, string queryField)
        {
            try
            {
                CodeManage_GenCodeBatch model = _CodeBatchService.GetModel(productBatchId);
                //string batch = model.Batch;//获取生码批次
                Organization_Enterprise Enterprise = _manager.GetEnterpriseModel(code);
                var batch = model.Batch;              
                string tabName = "nbcodemain." + AppConst.TablePrefix + code + batch;

                //获取对应的datatable
                DataTable codeTbl = _CodeBatchService.queryCode(tabName, queryField);
                bool fwIsExist = false;
                bool wlIsExist = false;
                // bool jfIsExist = false;
                //列名判断
                for (int i = 0; i < codeTbl.Columns.Count; i++)
                {
                    var columnName = codeTbl.Columns[i].ColumnName;
                    if (columnName == "Fw_Code")
                        fwIsExist = true;
                    if (columnName == "Wl_Code")
                        wlIsExist = true;
                    //if (columnName == "str")
                    //    wlIsExist = true;
                    //如果积分码存在 则在下面新增积分码信息
                    //if (columnName == "Fw_Code")
                    //    fwIsExist = true;
                }
                string key = AppConst.DigitCodeKey;
                string overrideLine = string.Empty;
                StringBuilder sb = new StringBuilder();
                DataRow[] dataRows = codeTbl.Select();
                foreach (DataRow item in dataRows)
                {
                    string result = null;
                    if (fwIsExist)
                    {
                        result += MiMa.Jiami(item["Fw_Code"].ToString(), key);
                    }
                     if (wlIsExist && fwIsExist)
                    {
                        result += "," + item["Wl_Code"].ToString() + ",";
                    }
                     if (wlIsExist && !fwIsExist)
                    {
                        result += item["Wl_Code"].ToString() + ",";
                    }
                    sb.Append(result.TrimEnd(',') + "\r\n");
                }
                //foreach (DataRow dr in codeTbl.Rows)
                //{
                //    string result = string.Empty;
                //    if (fwIsExist)
                //        result += MiMa.Jiami(dr["Fw_Code"].ToString(), key);
                //    if (wlIsExist && fwIsExist)
                //        result += "," + dr["Wl_Code"].ToString() + ",";
                //    if (wlIsExist && !fwIsExist)
                //        result += dr["Wl_Code"].ToString() + ",";
                //    overrideLine += result.TrimEnd(',') + "\r\n";
                //}
                codeTbl.Rows.Clear();
                GC.Collect();
                return Encoding.UTF8.GetBytes(sb.ToString());
            }
            catch//(Exception ex)
            {

                throw;
            }
        }

        #endregion



        #region 互查识别

        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="searchKey"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public JsonResult GetMutualCheckList(int pageIndex, int pageSize, string searchKey, string type)
        {
            PagedList<AntiFake_Digitcode> result = new PagedList<AntiFake_Digitcode>();
            int state = 1; //1:成功 0 失败
            try
            {  var sqls=string.Empty;
                var searchKeys = string.Empty;
                var sk =0;
                
                PagerModel pm = new PagerModel();
                pm.Page = pageIndex;
                pm.PageSize = pageSize;
                //查询语句判断
                pm.StrCondition = searchKey == null ? " ViewDel=0" : " ViewDel=0 and  EnterpriseName like '%" + searchKey + "%' ";
                if (!string.IsNullOrEmpty(searchKey))
                {
                    if (type == "Fw_Code" || type == "fw_Code")
                    {
                        searchKeys = MiMa.Jiemi(searchKey, AppConst.DigitCodeKey);
                       
                    }
                    else if (type == "wl_Code")
                    {
                        searchKeys = searchKey;
                      
                    }
                   
                    if (!string.IsNullOrEmpty(searchKeys))
                        {
                            pm.StrCondition = string.Format(" {0}='{1}'", type, searchKeys);
                        }

                    searchKey = searchKeys.Substring(0, 8);
                    sk = int.Parse(searchKey);

                  
                    if (!_digService.TabExists(searchKey))
                    {
                        state = 0;
                    }
                }
                if (!string.IsNullOrEmpty(searchKeys))
                {
                    sqls = string.Format(" {0}='{1}'", type, searchKeys);
                }
                var allotcode = _digService.allotcode(sqls, searchKeys);
                int allotcodes = int.Parse(allotcode);

                var HID = _digService.Heaid(sk);
              

                if (LogOnUser.EnterpriseId == 1 || HID == LogOnUser.EnterpriseId || allotcodes == LogOnUser.EnterpriseId)
                {
                    result = _digService.GetPagerList(ref pm, searchKey, LogOnUser.EnterpriseId, allotcodes);
                }
                if (result.PageData.Count == 0)
                {
                    return Json(result);
                }
                state = result == null ? 0 : 1;
                var stats = _digService.state(searchKey);
                if (stats == null)
                {
                    state = 0;
                }
            }

            catch
            {
                state = 0;
            }
            return Json(new { result, state }, JsonRequestBehavior.AllowGet);
        }

        #endregion


        #region 导码
        [HttpPost]
        public ActionResult leadCodeSave(HttpPostedFileBase file, string Flag, string enterId, string patch, int batchId, string eName)
        {
            CodeManage_GenCode codeModel = _Lecodeservice.GetModel_ID(batchId);
            var _file = file;
            string filePath = string.Empty;
            if (_file.ContentLength > 0)  // 如果有文件, 则保存到一个地址
            {
                string fileTextPath = AppConst.PathLeadCodeFile;
                filePath = string.Format("{0}{1}", fileTextPath, eName + batchId + ".txt");
                _file.SaveAs(Server.MapPath(filePath));//保存文件		
            }
            int result = _Lecodeservice.addWebFileUrl(patch, enterId, filePath, Flag, codeModel.CodeType);
            return Json(result);
        }
        #endregion
    }
}